package edu.spbu.eclipse.addressbook.andrpodk;
import java.io.*;
import java.util.*;

public class SaverLoader {	
	public static final String DELIMITER=(char)12+"";

	public ArrayList<Entry> load(String filePath)throws IOException,InvalidFileException {
		ArrayList<Entry> list = new ArrayList<Entry>();
		FileReader in = new FileReader(filePath);
		String s ="";
		int ch;
		ch = in.read();
		if(ch==-1) throw new InvalidFileException(InvalidFileException.EMPTY_FILE_TYPE);
		while (ch != -1){
			s = s + (char)ch;			
			ch = in.read();
			if ( ch == '\n'||ch==-1 ){
				StringTokenizer st=new StringTokenizer(s,DELIMITER,true);
				ArrayList<String> tokens=new ArrayList<String>();
				while(st.hasMoreTokens()){
					String currentToken=st.nextToken();
					if(!currentToken.equals(DELIMITER)){
						tokens.add(currentToken);
					}else{
						while(st.hasMoreTokens()&&
								(currentToken=st.nextToken()).equals(DELIMITER)){
							tokens.add("");					
						}
						if(currentToken.equals(DELIMITER)){
							tokens.add("");
						}else tokens.add(currentToken);								
					}			
				}
				if(tokens.size()!=4) 
					throw new InvalidFileException(InvalidFileException.INVALID_FORMAT_TYPE);
				list.add(new Entry(tokens.get(0),tokens.get(1),tokens.get(2),tokens.get(3)));
				s = "";
				ch = in.read();
			}
		}		
		in.close();		
		return list;
	}


	public void save(ArrayList<Entry> addressBook, String filePath)throws IOException{
		FileWriter out = new FileWriter(filePath);
		String s = "";		
		int j = 0;
		int size = addressBook.size();
		for (int i = 0; i < size; i++){
			s = addressBook.get(i).toString()+'\n';
			int l = s.length();
			for (j = 0; j < l ; j++){				
				out.write(s.charAt(j));
			}			
		}
		out.close();
	}
}

class InvalidFileException extends Exception{	
	private static final long serialVersionUID = 1L;
	public static final char EMPTY_FILE_TYPE=0;
	public static final char INVALID_FORMAT_TYPE=1;
	private int type;
	public InvalidFileException(int type) {
		super();
		this.type=type;
	}
	public int getType(){
		return type;
	}
}